﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using Kuaidi100.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Kuaidi100.Controllers
{

    [RoutePrefix("Test")]
    public class TestController : ApiController
    {
        /// <summary>
        /// 即时查询接口地址
        /// </summary>
        static string queryUrl = "http://poll.kuaidi100.com/";

        /// <summary>
        /// 归属公司智能判断
        /// </summary>
        static string queryComUrl = "http://www.kuaidi100.com/autonumber/auto?num={0}&key={1}";
        /// <summary>
        /// 公司编码
        /// </summary>
        string customer = "";
        /// <summary>
        /// 授权码
        /// </summary>
        string key = "";

        string callbackurl = "http:// :8710/test/callback?id={0}&nu={1}";

        [HttpGet, Route("Dingyue")]
        public string Dingyue(string nu)
        {
            string newUrl = string.Format(callbackurl, Guid.NewGuid(), nu);

            string param = "{\"company\":\"" + "ems" + "\",\"number\":\"" + nu + "\",\"key\":\"" + key + "\",\"parameters\":{\"callbackurl\":\"" + newUrl + "\",\"autoCom\":\"1\"}}";
            List<KeyValuePair<string, string>> formData = new List<KeyValuePair<string, string>>();
            formData.Add(new KeyValuePair<string, string>("schema", "json"));
            formData.Add(new KeyValuePair<string, string>("param", param));
            var str = HttpPost(queryUrl, "poll", formData);
            return str;
        }
        [HttpPost, Route("Callback")]
        public string Callback(Guid id, string nu)
        {
            var str = Request.Content.ReadAsStringAsync().Result;
            str = MyUrlDeCode(str, Encoding.UTF8);
            WriteFile(System.AppDomain.CurrentDomain.BaseDirectory + "\\log.txt", str);

            return "{\"result\":true,\"returnCode\":\"200\",\"message\":\"成功\"}";

        }
      
        /// <summary>
        /// 归属公司智能判断
        /// </summary>
        [HttpGet, Route("AutoQueryInfo")]
        public string AutoQueryInfo(string nu )
        {
            var str = HttpGet(string.Format(queryComUrl, nu, key));
            List<ComQueryModel> list = JsonConvert.DeserializeObject<List<ComQueryModel>>(str);
            string msg = "";
            foreach (var item in list)
            {
                msg += QueryInfo(item.comCode, nu);
            }
            return msg;
        }


        /// <summary>
        /// 归属公司智能判断
        /// </summary>
        [HttpGet, Route("QueryComInfo")]
        public string QueryComInfo(string nu )
        {
            return HttpGet(string.Format(queryComUrl, nu, key));
        }

        /// <summary>
        /// 快递信息查询
        /// </summary>
        /// <param name="com"></param>
        /// <param name="nu"></param>
        /// <returns></returns>
        [HttpPost, Route("QueryInfo")]
        public string QueryInfo(string com , string nu )
        {
            string param = "{\"com\":\"" + com + "\",\"num\":\"" + nu + "\"}";
            List<KeyValuePair<string, string>> formData = new List<KeyValuePair<string, string>>();
            formData.Add(new KeyValuePair<string, string>("customer", customer));
            formData.Add(new KeyValuePair<string, string>("sign", MD5(param + key + customer).ToUpper()));
            formData.Add(new KeyValuePair<string, string>("param", param));
            var str = HttpPost(queryUrl, "poll/query.do", formData);
            return str;
        }

        /// <summary>
        /// 同步请求post（键值对形式）
        /// </summary>
        /// <param name="uri">网络基址("http://localhost:59315")</param>
        /// <param name="url">网络的地址("/api/UMeng")</param>
        /// <param name="formData">键值对List<KeyValuePair<string, string>> formData = new List<KeyValuePair<string, string>>();formData.Add(new KeyValuePair<string, string>("userid", "29122"));formData.Add(new KeyValuePair<string, string>("umengids", "29122"));</param>
        /// <param name="charset">编码格式</param>
        /// <param name="mediaType">头媒体类型</param>
        /// <returns></returns>
        public static string HttpPost(string uri, string url, List<KeyValuePair<string, string>> formData = null, string charset = "utf-8", string mediaType = "application/x-www-form-urlencoded")
        {
            string tokenUri = url;
            var client = new HttpClient();
            client.BaseAddress = new Uri(uri);
            HttpContent content = new FormUrlEncodedContent(formData);
            content.Headers.ContentType = new MediaTypeHeaderValue(mediaType);
            content.Headers.ContentType.CharSet = charset;
            for (int i = 0; i < formData.Count; i++)
            {
                content.Headers.Add(formData[i].Key, formData[i].Value);
            }
            var res = client.PostAsync(tokenUri, content);
            res.Wait();
            HttpResponseMessage resp = res.Result;
            var res2 = resp.Content.ReadAsStringAsync();
            res2.Wait();
            string token = res2.Result;
            return token;
        }
        /// <summary>
        /// 同步get请求
        /// </summary>
        /// <param name="url">链接地址</param>   
        /// <param name="formData">写在header中的键值对</param>
        /// <returns></returns>
        public static string HttpGet(string url, List<KeyValuePair<string, string>> formData = null)
        {
            HttpClient httpClient = new HttpClient();

            var request = new HttpRequestMessage()
            {
                RequestUri = new Uri(url),
                Method = HttpMethod.Get,
            };

            var res = httpClient.SendAsync(request);
            res.Wait();
            var resp = res.Result;
            Task<string> temp = resp.Content.ReadAsStringAsync();
            temp.Wait();
            return temp.Result;
        }
        public static string MD5(string inputStr)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] hashByte = md5.ComputeHash(Encoding.UTF8.GetBytes(inputStr));
            StringBuilder sb = new StringBuilder();
            foreach (byte item in hashByte)
                sb.Append(item.ToString("x").PadLeft(2, '0'));
            return sb.ToString();
        }

        /// <summary>
        /// 写文件
        /// </summary>
        /// <param name="Path">文件路径</param>
        /// <param name="Strings">文件内容</param>
        public static void WriteFile(string Path, string Strings)
        {

            if (!System.IO.File.Exists(Path))
            {
                System.IO.FileStream f = System.IO.File.Create(Path);
                f.Close();
                f.Dispose();
            }
            System.IO.StreamWriter f2 = new System.IO.StreamWriter(Path, true, System.Text.Encoding.UTF8);
            f2.WriteLine(Strings);
            f2.Close();
            f2.Dispose();
        }

        public static string MyUrlDeCode(string str, Encoding encoding)
        {
            if (encoding == null)
            {
                Encoding utf8 = Encoding.UTF8;
                //首先用utf-8进行解码                    
                string code = HttpUtility.UrlDecode(str.ToUpper(), utf8);
                //将已经解码的字符再次进行编码.
                string encode = HttpUtility.UrlEncode(code, utf8).ToUpper();
                if (str == encode)
                    encoding = Encoding.UTF8;
                else
                    encoding = Encoding.GetEncoding("gb2312");
            }
            return HttpUtility.UrlDecode(str, encoding);
        }

    }
}
